package mysql

import (
	"crypto/md5"
	"fmt"
	"io"
)

// UserLogin 用户登录
func UserLogin(mobile string) (bool, int, string) {
	var u User
	db.Table("users").Where("mobile = ?", mobile).First(&u)
	if u.Mobile == "" {
		return false, 0, ""
	}
	return true, int(u.ID), u.Password
}

// CreateUser 创建用户
func CreateUser(User User) User {
	db.Create(&User)
	return User
}

// SearchMobile 查找手机号
func SearchMobile(user User) User {
	db.Where("mobile =?", user.Mobile).First(&user)
	return user
}

// MobileLogin 手机号登录
func MobileLogin(user User) User {
	db.Where("mobile = ?", user.Mobile).First(&user)
	return user
}

// UserModifyAvatar 修改头像
func UserModifyAvatar(user User) User {
	db.Model(&user).Update("avatar_url", user.AvatarUrl)
	return user
}

// GetUser 获取用户信息
func GetUser(id int64) User {
	var u User
	u.ID = uint(id)
	db.First(&u)
	return u
}

// SetPassword 设置密码
func SetPassword(id int, password string) User {
	user := User{}
	db.Where("id = ?", id).First(&user)
	if user.ID == 0 {
		return User{}
	}
	h := md5.New()
	io.WriteString(h, password)
	user.Password = fmt.Sprintf("%x", h.Sum(nil))
	db.Where("id = ?", user.ID).Save(&user)
	return user
}
